//
//  SampuxSetAliasView.m
//  Sampux
//
//  Created by rzm on 16/7/6.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxSetAliasView.h"

@interface SampuxSetAliasView ()<UITextFieldDelegate>

@property (nonatomic, strong) UIView *backView;

@property (nonatomic, strong) UILabel *lab ;
@end

@implementation SampuxSetAliasView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setEquipAlisa:) name:NOTIFICATION_RESPONSE_DEVICE_RENAME object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editDeviceUser:) name:NOTIFICATION_RESPONSE_EDIT_DEVICE_USER object:nil];

        [self loadUI];
    }
    return self;
}
- (void)loadUI
{
    CGFloat font = 8.;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    }else if (IS_IPHONE_5_OR_LESS)
    {
        font = 14.;
    }else if (IS_IPHONE_6)
    {
        font = 16.;
    }else
    {
        font = 17.;
    }

    UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self addSubview:view];
    view.backgroundColor = THBlackAlplaColor(0.6);
    view.alpha = 1;

    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(self.width *0.1, self.height * 0.3, self.width*0.8 ,self.height * 0.3)];
    [self addSubview:backView];
    self.backView = backView;
    backView.backgroundColor = [UIColor colorWithHex:0xff9a9a9d];
    [backView setCorner:5];
//    backView.alpha = 0.8;
    
    UILabel *lab = [UILabel createLabelWithText:@"设备更名" frame:CGRectMake(0, 0, backView.width, backView.height * 0.2) font:THFont(font)];
    lab.textAlignment = NSTextAlignmentCenter;
    lab.textColor = THSystemWhiteColor;
    [backView addSubview:lab];
    lab.backgroundColor = THDeFaultBlueColor;
    self.lab = lab;
//      _teleView = [[SampuxCustomTextFiledView alloc]initWithFrame:CGRectMake(backView.width/2 - Sampux6WScale(220)/2 , CGRectGetMaxY(lab.frame) + backView.height * 0.1,  Sampux6WScale(220), Sampux6HScale(SampuxCustomH))];
    _aliasView = [[SPDeleteTextFiledView alloc]initWithFrame:CGRectMake(backView.width/2 - Sampux6WScale(250)/2, CGRectGetMaxY(lab.frame) + backView.height *0.12, Sampux6WScale(250), Sampux6HScale(SampuxCustomH))];
    [_aliasView createDeleteTextFiledWithPlaceholder:@"输入别名" andLeftImage:@"feedBackCode" andRightImage:@"delete"];
    [backView addSubview:_aliasView];
    _aliasView.textFiled.delegate = self;
    _aliasView.textFiled.keyboardType = UIKeyboardTypeDefault;
    
    _aliasF = [UITextField createTextFieldWithRect:CGRectMake(backView.width * 0.05, CGRectGetMaxY(lab.frame) + backView.height *0.12, backView.width *0.9, backView.height * 0.2) andPlaceholder:@"输入别名" andLeftImage:@"reminder"];
//    [backView addSubview:_aliasF];
    
    UIButton *yesBtn = [UIButton createButtonWithTitle:@"确定" frame:CGRectMake(backView.width * 0.2, _aliasView.bottom + Sampux6WScale(30), backView.width* 0.6, backView.height * 0.2) titleFont:THFont(font) titleColor:THDeFaultBlueColor];
    [backView addSubview:yesBtn];
    [yesBtn addTarget:self action:@selector(yesBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [yesBtn setCorner: yesBtn.height/2];
    yesBtn.layer.borderWidth = 1;
    yesBtn.layer.borderColor = THWhiteAlplaColor(0.6).CGColor;
    backView.height = yesBtn.bottom + Sampux6WScale(30);
}

- (void)yesBtnClick
{
    [self removeView];

    if ([_aliasView.textFiled.text isEqualToString:@""]||_aliasView.textFiled.text.length == 0) {
//        [MBProgressHUD showError:@"请输入别名"];
        if (self.aliasType == SampuxSetAliasView_Device) {
            [GBInterMaster_CommForSystem requestDeviceRename:0 withDeviceAccount:self.model.accountStr withDeviceName:self.model.accountStr];
        }else
        {
            [GBInterMaster_CommForSystem requestEditDeviceUser:0 withDeviceAccount:self.configmodel.deviceAccount withUserAccount:self.info.userAccount withUserAlias:self.info.userAccount];
        }
    }else
    {
        if (self.aliasType == SampuxSetAliasView_Device) {
            [GBInterMaster_CommForSystem requestDeviceRename:0 withDeviceAccount:self.model.accountStr withDeviceName:_aliasView.textFiled.text];
        }else
        {
            [GBInterMaster_CommForSystem requestEditDeviceUser:0 withDeviceAccount:self.configmodel.deviceAccount withUserAccount:self.info.userAccount withUserAlias:_aliasView.textFiled.text];
        }
    }
}

- (void)setAliasType:(SampuxSetAliasView_Type)aliasType
{
    _aliasType = aliasType;
    if (_aliasType == SampuxSetAliasView_Device) {
        self.lab.text = @"设备更名";
    }else
    {
       self.lab.text = @"好友备注";
    }
}
#pragma -mark 输入框代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    CGFloat keyboardHeight = 216.0f;
    self.frame = CGRectMake(0, -keyboardHeight/6 , self.width, self.height);
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGFloat ly = [touch locationInView: self.backView].y;
    if ( ly < 0 || ly > self.backView.height ) { //点标题栏也会消失，点其他地方捕捉不到了
        [self removeView];
    }
    [super touchesBegan:touches withEvent:event];
}

- (void)removeView
{
//    dispatch_async(dispatch_get_main_queue(), ^{
    [self removeFromSuperview];
//    });
}

- (void)setEquipAlisa:(NSNotification *)notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"setEquipAlisa == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0)
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setEquipAlisa" object:self.aliasView.textFiled.text];
        if (self.alisaDelegate &&[self.alisaDelegate respondsToSelector:@selector(sendAlisaStr:)]) {
            [self.alisaDelegate sendAlisaStr:self.aliasView.textFiled.text];
        }
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"设置别名失败"];

//        [MBProgressHUD showError:@"设置别名失败"];
    }
}

- (void)editDeviceUser:(NSNotification *)notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@" editDeviceUser == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0)
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setParameterSuccess" object:self.aliasView.textFiled.text];
        [SVProgressHUD showSuccessWithStatus:@"编辑使用者成功"];
//        [MBProgressHUD showError:@"编辑使用者成功"];
        if (self.alisaDelegate &&[self.alisaDelegate respondsToSelector:@selector(sendAlisaStr:)]) {
            [self.alisaDelegate sendAlisaStr:self.aliasView.textFiled.text];
        }
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"编辑使用者失败"];
//        [MBProgressHUD showError:@"编辑使用者失败"];
    }

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
